package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.adapter.BrandOrderAdapter;
import com.longqinuo.mycarservice.adapter.DefaultOrderAdapter;
import com.longqinuo.mycarservice.adapter.HotBrandAdapter;
import com.longqinuo.mycarservice.adapter.PriceAgeAdapter;
import com.longqinuo.mycarservice.adapter.SecondCarAdapter;
import com.longqinuo.mycarservice.entity.CarBrand;
import com.longqinuo.mycarservice.entity.HotBrand;
import com.longqinuo.mycarservice.entity.SecondCar;
import com.longqinuo.mycarservice.utils.ComparatorPersonToPinYin;
import com.longqinuo.mycarservice.utils.PathUtils;
import com.longqinuo.mycarservice.utils.SpaceItemDecoration;
import com.longqinuo.mycarservice.view.LruImageCache;

import net.sourceforge.pinyin4j.PinyinHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SecondCarFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SecondCarFragment extends Fragment implements View.OnClickListener,AdapterView.OnItemClickListener {
    private ImageView mBack;
    private TextView mTitle;
    private ImageView mEdit;

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView mRecyclerView;
    private int lastVisibleItem ;  //最后一个可见Item的索引值
    private ListView orderLv;

    private SecondCarAdapter mAdapter;
    private PriceAgeAdapter priceAdapter;  //价格适配器
    private PriceAgeAdapter mileageAdapter;  //里程适配器
    private PriceAgeAdapter ageAdapter;  //车龄适配器


    private List<SecondCar> mList;
    private LinearLayoutManager layoutManager;
    private FragmentManager manager;
    private FragmentTransaction mTransaction;

    private static RequestQueue queue;
    private static ImageLoader imageLoader;
    private DefaultOrderAdapter orderAdapter;  //默认排序适配器

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private PopupWindow popupWindow;

    private OnFragmentInteractionListener mListener;
    private LinearLayout ll_default_order;
    private LinearLayout ll_car_brand;
    private LinearLayout ll_car_price_age;
    private TextView tv_default_order;
    private ImageView iv_default_order;
    private TextView tv_car_brand;
    private ImageView iv_car_brand;
    private TextView tv_car_price_age;
    private ImageView iv_car_price_age;
    private View mFlagView;

    private List<HotBrand> hotList; //热门品牌集合
    private List<CarBrand> brandList;
    private List<String> carTypes;
    private Map<String,String> map = new HashMap<>();   //post请求参数集合
    private boolean isCollect =false;
    public SecondCarFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SecondCarFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SecondCarFragment newInstance(String param1, String param2) {
        SecondCarFragment fragment = new SecondCarFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        init();
    }
    private void init() {
        queue = Volley.newRequestQueue(getActivity());
        LruImageCache lruImageCache = LruImageCache.instance();
        imageLoader = new ImageLoader(queue,lruImageCache);

        manager = getActivity().getSupportFragmentManager();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_second_car, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {


        mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_second_car_list);
        swipeRefreshLayout=(SwipeRefreshLayout)view.findViewById(R.id.swipe_refresh_second_car) ;
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,R.color.colorPrimaryDark,R.color.colorAccent);
        swipeRefreshLayout.setProgressViewOffset(false, 0,
                (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));

        mBack = (ImageView) view.findViewById(R.id.iv_top_back);
        mTitle = (TextView) view.findViewById(R.id.tv_top_title);
        mEdit = (ImageView) view.findViewById(R.id.iv_top_option);

        mBack.setOnClickListener(this);
        mTitle.setText("二手放心车");
        mEdit.setVisibility(View.INVISIBLE);


        mFlagView = view.findViewById(R.id.v_pop_flag);
        ll_default_order = (LinearLayout) view.findViewById(R.id.ll_default_order);
        ll_default_order.setOnClickListener(this);
        ll_car_brand = (LinearLayout) view.findViewById(R.id.ll_car_brand);
        ll_car_brand.setOnClickListener(this);
        ll_car_price_age = (LinearLayout) view.findViewById(R.id.ll_car_price_age);
        ll_car_price_age.setOnClickListener(this);

        tv_default_order = (TextView) view.findViewById(R.id.tv_default_order);
        iv_default_order = (ImageView) view.findViewById(R.id.iv_default_order);
        tv_car_brand = (TextView) view.findViewById(R.id.tv_car_brand);
        iv_car_brand = (ImageView) view.findViewById(R.id.iv_car_brand);
        tv_car_price_age = (TextView) view.findViewById(R.id.tv_car_price_age);
        iv_car_price_age = (ImageView) view.findViewById(R.id.iv_car_price_age);
        initData();
    }

    private void initData() {
        mList = new ArrayList<>();
        carTypes = new ArrayList<>();
        mAdapter = new SecondCarAdapter(mList, R.layout.second_car_item_layout,imageLoader);

        layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        int space = getResources().getDimensionPixelSize(R.dimen.recycler_divede_line);
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(space));


        mAdapter.setOnItemClickListener(new SecondCarAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                mTransaction = manager.beginTransaction();
                mTransaction.add(R.id.ll_main_layout, SecondInfoFragment.newInstance(mList.get(position).getId()+"",""), "SecondInfo");
                mTransaction.addToBackStack("SecondInfo");
                mTransaction.commit();
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        new GetData().execute();      //请求网络 查找车辆
        setListener();  //设置下拉刷新监听器
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
//                0：当前屏幕停止滚动；1时：屏幕在滚动 且 用户仍在触碰或手指还在屏幕上；2时：随用户的操作，屏幕上产生的惯性滑动；
                //               滑动状态停止并且剩余两个item时自动加载
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem +2>=layoutManager.getItemCount()) {  //触发上啦加载
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //                获取加载的最后一个可见视图在适配器的位置。
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();

            }

        });
    }
    private void setListener() {  //设置下拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new GetData().execute();
            }

        });
    }
    private void queryCarType() {  //查找车辆类型
        carTypes.clear();
        JsonObjectRequest typeRequest = new JsonObjectRequest(PathUtils.CAR_TYPE, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d(">>>>>", "车辆类型"+jsonObject.toString());

                try {
                    int code = jsonObject.getInt("code");

                    if (code==0) {
                        JSONArray array = jsonObject.getJSONArray("data");
                        for (int i = 0; i < array.length(); i++) {
                            String s = (String) array.get(i);
                            carTypes.add(s);
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        queue.add(typeRequest);
    }
    private class GetData extends AsyncTask<Void, Void, Void> {  //异步任务 请求网络

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            swipeRefreshLayout.setRefreshing(true);
        }

        @Override
        protected Void doInBackground(Void... params) {
            mList.clear();
            requestCar();  //查询车辆
            queryCarType();  //获取车辆类型
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            swipeRefreshLayout.setRefreshing(false);
        }
    }
    private void requestCar() {  //请求查找车辆

        StringRequest request = new StringRequest(Request.Method.POST,PathUtils.QUERY_CAR, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Gson gson=new Gson();
                String jsonData = null;
                try {

                    JSONObject jsonObject = new JSONObject(s);
                    int code = jsonObject.getInt("code");
                    if (code==0) {
                        jsonData = jsonObject.getString("data");
                        List<SecondCar> carList = gson.fromJson(jsonData, new TypeToken<List<SecondCar>>(){}.getType());
                        mList.addAll(carList);
                        mAdapter.notifyDataSetChanged();

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(">>>>>","查找车辆"+volleyError.toString());
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                return map;
            }
        };
        queue.add(request);

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    private View getOrderView() {   //填充 排序 布局
        View view = View.inflate(getActivity(),R.layout.default_order_layout,null);
        orderLv = (ListView) view.findViewById(R.id.lv_default_order);
        String[] orders = getActivity().getResources().getStringArray(R.array.orders);
        List<String> orderList = Arrays.asList(orders);

        orderAdapter = new DefaultOrderAdapter(getActivity(),orderList);
        orderLv.setAdapter(orderAdapter);
        orderLv.setOnItemClickListener(this);
        return view;
    }
    private View getBrandView() {   //填充 车辆品牌 布局
        View view = View.inflate(getActivity(),R.layout.car_brand_layout,null);
        TextView noBrand = (TextView) view.findViewById(R.id.tv_no_brand);
        noBrand.setOnClickListener(this);
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rv_car_brand_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        hotList = new ArrayList<>();  //热门品牌 集合
        for (int i = 0; i < 8; i++) {
            HotBrand hotBrand = new HotBrand(R.mipmap.logo,carTypes.get(i));
            hotList.add(hotBrand);
        }
        HotBrandAdapter adapter = new HotBrandAdapter(hotList,R.layout.hot_brand_item_layout);

        adapter.setOnItemClickListener(new HotBrandAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                if (map.containsKey("type")) {
                    map.remove("type");
                }
                map.put("type",hotList.get(position).getName());  //选择热门品牌
                requestCar();  //刷新数据
                popupWindow.dismiss();
            }
        });
        recyclerView.setAdapter(adapter);

        ListView brandView = (ListView) view.findViewById(R.id.lv_car_brand_list);
        initBrandData();  //初始化 车辆品牌 数据
        dataDeal();
        BrandOrderAdapter brandOrderAdapter = new BrandOrderAdapter(getActivity(),brandList);
        brandView.setAdapter(brandOrderAdapter);
        brandView.setOnItemClickListener(this);
        return view;
    }
    private void initBrandData() {  //初始化 车辆品牌 数据
        brandList = new ArrayList<CarBrand>();
        for (int i = 0; i < carTypes.size(); i++) {
            CarBrand carBrand = new CarBrand();
            carBrand.setName(carTypes.get(i));
            brandList.add(carBrand);
        }

    }
    private void dataDeal() {
        // 取得拼音
        for (CarBrand c : brandList) {
            // 取得拼音
            c.setPinYinName(getPinYinNameHeader(c.getName()));
        }
        // 排序
        Collections.sort(brandList, new ComparatorPersonToPinYin());
        //插入值
        String tempCh = "1";
        for (int i =0; i< brandList.size(); i ++  ) {
            if (!tempCh.equals(brandList.get(i).getPinYinName().charAt(0)+"")) {
                brandList.add(i, new CarBrand(0,"",brandList.get(i).getPinYinName().charAt(0)+""));
                tempCh = brandList.get(i).getPinYinName().charAt(0)+"";
            }
        }
    }
    // 得到名字拼音头字母
    public String getPinYinNameHeader(String str) {
        String convert = "";
        for (int i = 0; i < str.length(); i++) {
            char word = str.charAt(i);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert;
    }
    private View getPriceView() {   //价格 里程 车龄
        View view = View.inflate(getActivity(),R.layout.car_price_age_layout,null);
        GridView priceView = (GridView) view.findViewById(R.id.gv_car_price_second);
        List<String> priceList = new ArrayList<>();
        for (int i = 0; i < PathUtils.prices.length; i++) {
            if (i>0) {
                priceList.add(PathUtils.prices[i]+"万");
            } else {
                priceList.add(PathUtils.prices[0]);
            }
        }
        priceAdapter = new PriceAgeAdapter(getActivity(),priceList);
        priceView.setAdapter(priceAdapter);
        priceView.setOnItemClickListener(this);

        GridView mileageView = (GridView) view.findViewById(R.id.gv_car_mileage_second);
        List<String> mileageList = new ArrayList<>();
        for (int i = 0; i < PathUtils.mileages.length; i++) {
            if (i>0) {
                mileageList.add(PathUtils.mileages[i]+"万以内");
            } else {
                mileageList.add(PathUtils.mileages[0]);
            }
        }
        mileageAdapter = new PriceAgeAdapter(getActivity(),mileageList);
        mileageView.setAdapter(mileageAdapter);
        mileageView.setOnItemClickListener(this);

        GridView ageView = (GridView) view.findViewById(R.id.gv_car_age_second);
        List<String> ageList = new ArrayList<>();
        for (int i = 0; i < PathUtils.ages.length; i++) {
            if (i>0) {
                ageList.add(PathUtils.ages[i]+"年");
            } else {
                ageList.add(PathUtils.ages[0]);
            }
        }
        ageAdapter = new PriceAgeAdapter(getActivity(),ageList);
        ageView.setAdapter(ageAdapter);
        ageView.setOnItemClickListener(this);
        return view;
    }

    @Override
    public void onClick(View v) {
        int colorBlue = getResources().getColor(R.color.colorTabFontSelected);

        switch (v.getId()) {
            case R.id.iv_top_back:
                manager.popBackStack();
                break;
            case R.id.ll_default_order:  //排序popWindow
                View view = getOrderView();
                createPopupWindow(view,v);
                tv_default_order.setTextColor(colorBlue);
                iv_default_order.setImageResource(R.mipmap.up_triangle_blue);
                break;
            case R.id.ll_car_brand:     //品牌popWindow
                View brandPopView = getBrandView();
                createPopupWindow(brandPopView,v);
                tv_car_brand.setTextColor(colorBlue);
                iv_car_brand.setImageResource(R.mipmap.up_triangle_blue);
                break;
            case R.id.ll_car_price_age:     //价格popWindow
                View pricePopView = getPriceView();

                createPopupWindow(pricePopView,v);
                tv_car_price_age.setTextColor(colorBlue);
                iv_car_price_age.setImageResource(R.mipmap.up_triangle_blue);
                break;
            case R.id.tv_no_brand:    //不限品牌
                if (map.containsKey("type")) {
                    map.remove("type");
                }
                new GetData().execute();  //刷新数据
                popupWindow.dismiss();
                break;
        }
    }
    private void createPopupWindow(View view, final View linearLayout) {
        final int colorGrey = getResources().getColor(R.color.colorGrayFont);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);

        mRecyclerView.setAlpha(0.2f);

        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAsDropDown(mFlagView,0,0);
        popupWindow.update();
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mRecyclerView.setAlpha(1.0f);
                switch (linearLayout.getId()) {
                    case R.id.ll_default_order:
                        tv_default_order.setTextColor(colorGrey);
                        iv_default_order.setImageResource(R.mipmap.down_triangle_grey);
                        break;
                    case R.id.ll_car_brand:
                        tv_car_brand.setTextColor(colorGrey);
                        iv_car_brand.setImageResource(R.mipmap.down_triangle_grey);
                        break;
                    case R.id.ll_car_price_age:
                        tv_car_price_age.setTextColor(colorGrey);
                        iv_car_price_age.setImageResource(R.mipmap.down_triangle_grey);
                        break;
                }

            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.lv_default_order:   //默认排序
                orderAdapter.selectPosition(position);
                orderAdapter.notifyDataSetChanged();   //点击单项设置选中状态

                if (position!=0) {
                    if (map.containsKey("order")) {
                        map.remove("order");
                    }
                    map.put("order",position+"");
                    new GetData().execute();   //按照排序请求车辆；
                } else {
                    if (map.containsKey("order")) {
                        map.remove("order");
                    }
                    new GetData().execute();   //按照排序请求车辆；
                }
                popupWindow.dismiss();
                break;
            case R.id.lv_car_brand_list:
                CarBrand c = brandList.get(position);
                String name = c.getName();
                if (!TextUtils.isEmpty(name)) {
                    if (map.containsKey("type")) {
                        map.remove("type");
                    }
                    map.put("type",brandList.get(position).getName());  //选择品牌
                    new GetData().execute();  //刷新数据
                }
                popupWindow.dismiss();
                break;
            case R.id.gv_car_price_second:  //价格
                priceAdapter.selectPricePosition(position);
                priceAdapter.notifyDataSetChanged();   //点击单项设置选中状态

                if (position!=0) {
                    if (map.containsKey("s_price")) {
                        map.remove("s_price");
                    }
                    map.put("s_price",PathUtils.prices[position]);
                    new GetData().execute();   //按照排序请求车辆；
                } else{
                    if (map.containsKey("s_price")) {
                        map.remove("s_price");
                    }
                    new GetData().execute();   //按照排序请求车辆；
                }
                popupWindow.dismiss();
                break;
            case R.id.gv_car_mileage_second:  //里程
                mileageAdapter.selectMileagePosition(position);
                mileageAdapter.notifyDataSetChanged();   //点击单项设置选中状态

                if (position!=0) {
                    if (map.containsKey("km")) {
                        map.remove("km");
                    }
                    map.put("km",PathUtils.mileages[position]);
                    new GetData().execute();   //按照排序请求车辆；
                } else {
                    if (map.containsKey("km")) {
                        map.remove("km");
                    }
                    new GetData().execute();   //按照排序请求车辆；
                }
                popupWindow.dismiss();
                break;
            case R.id.gv_car_age_second:  //车龄
                ageAdapter.selectAgePosition(position);
                ageAdapter.notifyDataSetChanged();   //点击单项设置选中状态

                if (position!=0) {
                    if (map.containsKey("s_date")) {
                        map.remove("s_date");
                    }
                    map.put("s_date",PathUtils.ages[position]);
                    new GetData().execute();   //按照排序请求车辆；
                } else {
                    if (map.containsKey("s_date")) {
                        map.remove("s_date");
                    }
                    new GetData().execute();   //按照排序请求车辆；
                }
                popupWindow.dismiss();
                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
